package com.hc.likelistenmusic.activity

import android.Manifest
import android.app.Dialog
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.hc.likelistenmusic.R
import com.hc.likelistenmusic.util.XPermissionUtil
import com.hc.likelistenmusic.util.XPermissionUtil.XPermissionListener
import com.hc.likelistenmusic.view.CommonDialog
import com.hjq.permissions.XXPermissions

class SplashActivity : AppCompatActivity() {
    lateinit var mTv_as_local: TextView
    lateinit var mTv_as_online: TextView
    lateinit var mTv_as_jump_set: TextView
    lateinit var mIv_as_back: ImageView
    lateinit var mExitDialog: CommonDialog
    var mExitTime = -1L
    var mBack = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val window = window
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = resources.getColor(R.color.color_theme)
        window.navigationBarColor = resources.getColor(R.color.color_theme)
        setContentView(R.layout.activity_splash)

        init()
        mBack = intent.getBooleanExtra("mBack",false)
    }

    override fun onBackPressed() {
        if (mExitTime == -1L) {
            mExitTime = System.currentTimeMillis()
            showToast(resources.getString(R.string.string_exit_info))
        } else {
            val currentTimeMillis = System.currentTimeMillis()
            if (currentTimeMillis - mExitTime < 2000) {
                finish()
            } else {
                mExitTime = currentTimeMillis
                showToast(resources.getString(R.string.string_exit_info))
            }
        }
    }
    fun init() {
        mTv_as_local = findViewById(R.id.tv_as_local)
        mTv_as_online = findViewById(R.id.tv_as_online)
        mTv_as_jump_set = findViewById(R.id.tv_as_jump_set)
        mIv_as_back = findViewById(R.id.iv_as_back)
        mTv_as_local.setOnClickListener {
            mTv_as_local.setTextColor(getColor(R.color.color_green))
            mTv_as_online.setTextColor(getColor(R.color.color_white))
            checkLocalPermissions()
        }
        mTv_as_online.setOnClickListener {
            mTv_as_local.setTextColor(getColor(R.color.color_white))
            mTv_as_online.setTextColor(getColor(R.color.color_green))
            mTv_as_jump_set.visibility = GONE
            checkOnlinePermissions()
        }
        mTv_as_jump_set.setOnClickListener {
            mTv_as_jump_set.visibility = GONE
            mTv_as_local.setTextColor(getColor(R.color.color_white))
            mTv_as_online.setTextColor(getColor(R.color.color_white))
            XXPermissions.startPermissionActivity(this,generateExternalStorage())
        }
        mIv_as_back.setOnClickListener {
            if(!mExitDialog.isShowing){
                mExitDialog.show()
            }
        }
        mExitDialog = CommonDialog.Builder()
            .setContext(this)
            .setLayoutId(R.layout.dialog_exit)
            .setLeftViewId(R.id.negative)
            .setRightViewId(R.id.positive)
            .setCancelable(false)
            .setDefaultListener(object : CommonDialog.CommonDialogDefaultOnClickListener {
                override fun onLeftViewClick(dialog: Dialog?) {
                    dialog?.dismiss()
                }

                override fun onCommonViewClick(dialog: Dialog?) {

                }

                override fun onRightViewClick(dialog: Dialog?) {
                    dialog?.dismiss()
                    finish()
                }
            }).build()
    }

    fun generateExternalStorage():List<String>{
        val external_storage = mutableListOf<String>()
        if((applicationInfo.targetSdkVersion) >= Build.VERSION_CODES.TIRAMISU){
            external_storage.let {
                it.add(Manifest.permission.READ_MEDIA_IMAGES)
                it.add(Manifest.permission.READ_MEDIA_VIDEO)
                it.add(Manifest.permission.READ_MEDIA_AUDIO)
            }
        }else{
            external_storage.let {
                it.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                it.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
        }
        return external_storage
    }
    fun checkOnlinePermissions() {
        val permissions = mutableListOf<String>()
        permissions.let {
            it.add(Manifest.permission.READ_PHONE_STATE)
            if((applicationInfo.targetSdkVersion) >= Build.VERSION_CODES.TIRAMISU){
                it.add(Manifest.permission.POST_NOTIFICATIONS)
            }
        }
        XPermissionUtil.checkPermission(this,null,permissions, object :XPermissionListener{
            override fun permissionGranted(
                allGranted: Boolean,
                grantedList: MutableList<String>,
                grantedChineseList: MutableList<String>
            ) {
                startActivity(Intent(this@SplashActivity, OnlineMusicActivity::class.java))
                finish()
            }

            override fun permissionDenied(
                deniedList: MutableList<String>,
                deniedChineseList: MutableList<String>
            ) {
                dealOnlinePermissionDenied(false, deniedList)
            }

            override fun permissionForeverDenied(
                deniedList: MutableList<String>,
                deniedChineseList: MutableList<String>
            ) {
                dealOnlinePermissionDenied(true, deniedList)
            }
        })
    }

    fun checkLocalPermissions() {
        val permissions = mutableListOf<String>()
        val external_storage = generateExternalStorage()
        if ((applicationInfo.targetSdkVersion) >= Build.VERSION_CODES.TIRAMISU) {
            permissions.let {
                it.add(Manifest.permission.READ_MEDIA_IMAGES)
                it.add(Manifest.permission.READ_MEDIA_VIDEO)
                it.add(Manifest.permission.READ_MEDIA_AUDIO)
                it.add(Manifest.permission.READ_PHONE_STATE)
                it.add(Manifest.permission.POST_NOTIFICATIONS)
            }
        } else {
            permissions.let {
                it.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                it.add(Manifest.permission.READ_EXTERNAL_STORAGE)
                it.add(Manifest.permission.READ_PHONE_STATE)
            }
        }

        XPermissionUtil.checkPermission(this, null, permissions, object :
            XPermissionListener {
            override fun permissionGranted(
                allGranted: Boolean,
                grantedList: MutableList<String>,
                grantedChineseList: MutableList<String>
            ) {
                var save: Boolean
                if (allGranted) {
                    save = true
                } else {
                    save = grantedList.containsAll(external_storage)
                }
                if (save) {
                    startActivity(Intent(this@SplashActivity, LocalMusicActivity::class.java))
                    finish()
                }else{
                    mTv_as_jump_set.visibility = VISIBLE
                }
            }

            override fun permissionDenied(
                deniedList: MutableList<String>,
                deniedChineseList: MutableList<String>
            ) {
                dealLocalPermissionDenied(false, deniedList)
            }

            override fun permissionForeverDenied(
                deniedList: MutableList<String>,
                deniedChineseList: MutableList<String>
            ) {
                dealLocalPermissionDenied(true, deniedList)
            }
        })
    }

    fun dealLocalPermissionDenied(forever: Boolean, deniedList: MutableList<String>) {
        var save = false
        var phone = false
        deniedList.forEach {
            if (Manifest.permission.READ_PHONE_STATE == it) {
                phone = true
            }
            if (Manifest.permission.WRITE_EXTERNAL_STORAGE == it
                || Manifest.permission.READ_EXTERNAL_STORAGE == it
                || Manifest.permission.READ_MEDIA_IMAGES == it
                || Manifest.permission.READ_MEDIA_VIDEO == it
                || Manifest.permission.READ_MEDIA_AUDIO == it
            ) {
                save = true
            }
        }
        if (save && phone) {
            showToast(
                if (forever) {
                    resources.getString(R.string.string_permission_all_forever_denied)
                } else {
                    resources.getString(R.string.string_permission_all_denied)
                }
            )
            if(forever){
                mTv_as_jump_set.visibility = VISIBLE
            }
        } else if (save and !phone) {
            showToast(
                if (forever) {
                    resources.getString(R.string.string_permission_save_forever_denied)
                } else {
                    resources.getString(R.string.string_permission_save_denied)
                }
            )
            if(forever){
                mTv_as_jump_set.visibility = VISIBLE
            }
        } else if (!save and phone) {
            if(!mBack){
                showToast(
                    if (forever) {
                        resources.getString(R.string.string_permission_phone_forever_denied)
                    } else {
                        resources.getString(R.string.string_permission_phone_denied)
                    }
                )
            }
        }
    }

    fun dealOnlinePermissionDenied(forever: Boolean, deniedList: MutableList<String>) {
        var phone = false
        deniedList.forEach {
            if (Manifest.permission.READ_PHONE_STATE == it) {
                phone = true
            }
        }
        if(phone){
            if(!mBack){
                showToast(
                    if (forever) {
                        resources.getString(R.string.string_permission_phone_forever_denied)
                    } else {
                        resources.getString(R.string.string_permission_phone_denied)
                    }
                )
            }
        }
    }
    fun showToast(info: String) {
        Toast.makeText(applicationContext, info, Toast.LENGTH_LONG).show()
    }
}